<template>
  <div class="generation-stats">
    <!-- 任务列表 -->
    <div class="task-list">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <span>任务列表
              <span v-if="abnormal" style="color: red;font-size: 12px">({{errorMsg}})</span>
            </span>
            <div class="header-actions">
              <el-button
                type="primary"
                @click="refreshTasks"
                :loading="loading"
              >
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>
        <el-table
          class="m-top"
          stripe
          border
          row-key="id"
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            label="报表级别"
            align="center"
            prop="fileName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="学校"
            align="center"
            prop="schoolName"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.schoolName || "联考" }}
            </template>
          </el-table-column>
          <el-table-column
            label="生成进度"
            align="center"
            prop="percent"
            :show-overflow-tooltip="true"
          >
            <!-- <template slot-scope="scope">
            <el-progress :percentage="scope.row.percent" :show-text="false" />
          </template> -->
            <template slot-scope="scope">
              <el-progress
                :percentage="progress || 0"
                :status="progress == 100 ? 'success' : 'exception'"
                :stroke-width="26"
                :text-inside="true"
                text-color="#fff"
              />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="180"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click="downloadFile(scope.row)"
                :disabled="progress < 100"
                >下载文件</el-link
              >

              <!-- <el-link
                type="danger"
                @click="startGenerate(1, '重新')"
                :disabled="progress < 100"
                v-if="scope.$index == 0"
                >重新生成</el-link
              > -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="450px  "
      :before-close="handleClose"
    >
      <div style="padding: 0 20px">
        <div style="display: flex; line-height: 30px">
          <div>分析内容：</div>
          <el-checkbox-group v-model="checkedAnalysis">
            <el-checkbox label="上线分析">上线分析</el-checkbox>
            <el-checkbox label="成绩分析">成绩赋分</el-checkbox>
          </el-checkbox-group>
        </div>
        <div style="display: flex; margin-top: 20px; line-height: 30px">
          <div>生成形式：</div>
          <el-checkbox-group v-model="checkedGenerate">
            <el-checkbox label="成绩分析">成绩分析</el-checkbox>
            <el-checkbox label="PDF分析">PDF分析</el-checkbox>
            <el-checkbox label="卷面留痕">卷面留痕</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-if="generateType == 0"
          type="primary"
          @click="dialogVisible = false"
          >生成</el-button
        >
        <el-button
          v-if="generateType == 1"
          type="danger"
          @click="dialogVisible = false"
          >重新生成</el-button
        >
        <el-button type="info" @click="dialogVisible = false">返回</el-button>
      </span>
    </el-dialog>
    <div class="page-bottom">
      <div class="sel-box">
        <!-- <el-button @click="startGenerate(0,'开始')" type="primary" :disabled="progress>0"
          v-if="total<=1&&progress==0"
          :loading="progress<100&&progress>0">开始生成</el-button> -->
        <!-- 计算 1-->
        <el-button
          :loading="calculating"
          :disabled="calculating"
          type="primary"
          @click="startCalculate"
        >
          {{ calculating ? "计算中..." : "计算" }}
        </el-button>
        <!-- 开始生成 1-->
        <el-button
          @click="startGenerate(0, '开始')"
          type="primary"
          :disabled="progress > 0"
          v-if="total <= 1 && progress == 0"
          :loading="progress < 100 && progress > 0"
          >开始生成</el-button
        >
        <!-- 重新生成 1-->
        <el-button
          @click="startGenerate(1, '重新')"
          type="danger"
          :disabled="progress < 100||abnormal"
          v-else
          >
        重新生成
        </el-button>
        <!-- 取消-->
        <!-- <el-button
          @click="startGenerate(1, '取消', 1)"
          type="danger"
          :disabled="progress < 100"
          v-else
        >
        取消
        </el-button> -->
        <!-- 开始生成 -->
        <!-- <el-button
          @click="openGenerateDialog"
          type="primary"
          :disabled="progress > 0"
          v-if="total <= 1 && progress == 0"
          :loading="progress < 100 && progress > 0"
        >
          开始生成
        </el-button> -->

        <!-- 重新生成 -->
        <!-- <el-button
          @click="openReGenerateDialog"
          type="danger"
          :disabled="progress < 100"
          v-else
        >
          重新生成
        </el-button> -->
        <!-- <el-button @click="reGenerate" type="primary">全部重新生成</el-button> -->
        <!-- <el-button type="danger">删除结果</el-button> -->
      </div>
      <!-- <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
    </div>
    <!-- 计算弹窗 -->
    <!-- <el-dialog
      title="计算"
      :visible.sync="CalculateDialogVisible"
      width="400px"
    >
      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="赋分">
              <el-switch v-model="switchAssign"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线分析">
              <el-switch v-model="switchOnline"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="CalculateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="startGenerate(0, '开始')"
          >确定</el-button
        >
      </div>
    </el-dialog> -->
    <!-- 开始生成弹窗 -->
    <el-dialog
      title="生成成绩分析"
      :visible.sync="generateDialogVisible"
      width="400px"
    >
      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="赋分">
              <el-switch v-model="switchAssign"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线分析">
              <el-switch v-model="switchOnline"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="startGenerate(0, '开始')"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!-- 重新生成弹窗 -->
    <el-dialog
      title="重新生成成绩分析"
      :visible.sync="reGenerateDialogVisible"
      width="400px"
    >
      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="赋分">
              <el-switch v-model="switchAssign"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线分析">
              <el-switch v-model="switchOnline"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reGenerateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="startGenerate(1, '重新')"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "lodash";
import {
  generateScoreAnalysis,
  getScoreAnalysisList,
  getGenerationProgress,
  generateCalculateAll,
  getCalculateStatus,
} from "@/api/xmgl/cjgl";

export default {
  props: {
    xmxx: {
      type: Object,
      default: () => {},
    },
  },

  data() {
    return {
      destroyed: false,
      errorMsg: "",//生成报表异常信息
      abnormal: false,//生成报表异常
      fetchNum: 0,
      loading: false,
      activeName: "",

      tableData: [],

      timer: null,

      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogTitle: "",
      dialogVisible: false,
      generateType: 0, // 0 生成 1 重新生成
      checkedAnalysis: [], // 分析内容
      checkedGenerate: [], // 生成形式
      multipleSelection: [],
      multiple: true,
      progress: 0,
      // 弹窗控制
      generateDialogVisible: false,
      reGenerateDialogVisible: false,
      CalculateDialogVisible: false,
      // 开关
      switchAssign: true,
      switchOnline: true,
      calculating: false, // 按钮加载状态
      checkTimer: null, // 轮询定时器
    };
  },
  created() {
    this.activeName = this.activeName ? this.activeName : "cjfx";
    this.getList();
  },

  methods: {
    // 打开“计算”弹窗
    openCalculateDialog() {
      this.CalculateDialogVisible = true;
    },
    // 打开“开始生成”弹窗
    openGenerateDialog() {
      this.generateDialogVisible = true;
    },
    // 打开“重新生成”弹窗
    openReGenerateDialog() {
      this.reGenerateDialogVisible = true;
    },
    // 计算
    async startCalculate() {
      this.$confirm(`是否开始计算？`, "计算", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        this.calculating = true; // 开启加载状态

        try {
          const res = await generateCalculateAll({
            examId: this.xmxx.id,
            assignFlag: this.switchAssign ? 1 : 2,
            onlineFlag: this.switchOnline ? 1 : 2,
          });

          if (res.code === 200) {
            this.$message.success(`计算任务已启动，正在计算中...`);
            // 开始轮询计算状态
            this.startCheckStatus();
          } else {
            this.$message.error(`计算启动失败：${res.msg}`);
            this.calculating = false;
          }
        } catch (err) {
          this.$message.error("计算启动异常");
          this.calculating = false;
        }
      });
    },
    // 轮询计算状态
    startCheckStatus() {
      this.checkTimer = setInterval(async () => {
        try {
          const res = await getCalculateStatus({ examId: this.xmxx.id });
          if (res.code === 200) {
            const status = Number(res.data);
            // console.log("当前计算状态:", res.data);
            if (status === 0) {
              this.$message.success("计算完成");
              this.stopCheckStatus();
              this.calculating = false;
            } else if (status < 0) {
              this.$message.error("计算失败，请检查日志");
              this.stopCheckStatus();
              this.calculating = false;
            }
          }
        } catch (err) {
          console.error(err);
        }
      }, 5000); // 每5秒请求一次
    },

    stopCheckStatus() {
      if (this.checkTimer) {
        clearInterval(this.checkTimer);
        this.checkTimer = null;
      }
    },
    // 生成或重新生成
    // startGenerate(type, text) {
    //   this.$confirm(`是否${text}生成成绩分析？`, "成绩分析", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then(() => {
    //     generateScoreAnalysis({
    //       examId: this.xmxx.id,
    //       regen: type,
    //       assignFlag: this.switchAssign ? 1 : 0,
    //       onlineFlag: this.switchOnline ? 1 : 0,
    //     }).then((res) => {
    //       if (res.code === 200) {
    //         this.$message.success(`${text}生成成功`);
    //         this.generateDialogVisible = false;
    //         this.reGenerateDialogVisible = false;
    //         this.getList();
    //       }
    //     });
    //   });
    // },

    endTime() {
      this.fetchNum = 0;
      clearInterval(this.timer);
      this.timer = null;
    },
   async startTime() {
     // 调用查询进度接口
      if (this.destroyed) {
      console.log('组件已销毁,不调用计时器');
      return false;
     }
     if(this.tableData.length ==0){
      return false;
     }
        const feature=()=> getGenerationProgress(this.xmxx.id).then(async (res) => {
          this.fetchNum++
          if (res.code == 200) {
            this.progress = Number(res.data.split("%")[0]);

            if (this.tableData.length) {
              this.$set(
                this.tableData[0],
                "percent",
                Number(res.data.split("%")[0])
              );
            }
            // 更新进度，有100%的判断是否全部完成 调用 this.endTime();
            if (
            this.fetchNum>7&&
              Number(res.data.split("%")[0]) == 0
            ) {
              this.$message.warning("生成失败，请重新开始生成");
              this.endTime();

            }
            if (Number(res.data.split("%")[0]) == 100) {
              this.endTime();
              await getScoreAnalysisList({
                examId: this.xmxx.id,
                ...this.queryParams,
              }).then((res) => {
                if (res.code == 200) {
                  this.tableData = res.rows;
                  this.total = res.total;
                  this.tableData[0].percent = this.progress;
                }
              });
            }
          }
        }).catch((err)=>{
          console.log(Number(err.data.split("%")[0]),'wxd');
          this.errorMsg = err.msg;
          this.$nextTick(()=>{
            this.progress = Number(err.data.split("%")[0]);
          })
          this.abnormal = true;
          this.endTime();
          getScoreAnalysisList({
                examId: this.xmxx.id,
                ...this.queryParams,
              }).then((res) => {
                if (res.code == 200) {
                  this.tableData = res.rows;
                  this.total = res.total;
                  this.tableData[0].percent = this.progress;
                }
              });
        })
        feature()
      this.timer = setInterval(async () => {
        feature()
      }, 3000);
    },
    refreshTasks() {
      this.getList();
    },
    // 分页相关
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    downloadFile(subtask) {
      if (!subtask.ossUrl) {
        this.$message.warning("文件链接不存在");
        return;
      }

      const link = document.createElement("a");
      link.href = `${subtask.ossUrl}`;

      link.download = subtask.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    getList: debounce(function () {
      this.endTime();
      // this.activeName = this.active  Name?this.activeName:'cjfx';

      this.loading = true;
      getScoreAnalysisList({
        examId: this.xmxx.id,
        ...this.queryParams,
      })
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.rows;
            this.total = res.total;
            // if (res.total<=1) {
            this.startTime();
            // }
          }
        })
        .finally(() => {
          this.loading = false;
        });

      // generateScoreAnalysis({
      //   examId: this.xmxx.id,
      //   regen: this.generateType,
      // }).then((res) => {
      //   if (res.code == 200) {
      //     this.$message({
      //       type: 'success',
      //       message: '生成成功'
      //     });
      //     this.getList();
      //   }
      // })

      this.endTime();
      // 根据activeName调用接口;

      // this.loading = false;
      // 判断是否有生成中的数据，有过有 调用this.startTime();
    }, 600),
    activeChange() {
      this.tableData = [];
      this.queryParams.pageNum = 1;
      this.getList();
    },

    cxsc(row) {
      // 重新生成后  调用this.startTime()
    },
    handleClose() {
      this.dialogVisible = false;
      this.generateType = 0;
    },
    startGenerate(index, text) {
      this.$confirm(`是否${text}生成成绩分析？`, "成绩分析", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.fetchNum = 5;
        this.abnormal = false;
        generateScoreAnalysis({
          examId: this.xmxx.id,
          regen: index,
          assignFlag: this.switchAssign ? 1 : 2,
          onlineFlag: this.switchOnline ? 1 : 2,
        }).then((res) => {
          if (res.code == 200) {
            this.getList();
          }
        });
        this.getList();
      });
    },
    reGenerate() {
      this.dialogTitle = "全部重新生成";
      this.dialogVisible = true;
      this.generateType = 1;
    },
    handleSelectionChange(selection) {
      console.log(selection, "selection");

      this.multipleSelection = selection;
      this.multiple = !selection.length;
    },
  },
  beforeDestroy() {
    console.log('组件销毁前');
    this.destroyed = true;
    this.endTime();
    this.stopCheckStatus();
  },
};
</script>

<style scope>
.generation-stats {
  padding: 20px;
}
.task-list {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
